package com.mrx.java8.lambda;

import com.alibaba.fastjson.JSON;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8内置的四大核心函数式接口
 *
 * Consumer<T> : 消费型接口
 *      void accept(T t);
 *
 * Supplier<T> : 供给型接口
 *      T get();
 *
 * Function<T,R> : 函数型接口
 *      R apply(T t);
 *
 * Predicate<T> : 断言型接口
 *      boolean test(T t);
 */
public class TestLambda3 {
    /** 1 Consumer<T> 消费型接口*/
    @Test
    public void test1(){
        happy(10000,m-> System.out.println("Hello Lambda "+m));
    }

    public void happy(double money, Consumer<Double> consumer){
        consumer.accept(money);
    }


    /** 2 Supplier<T> 供给型接口：*/
    @Test
    public void test2(){
        List<Integer> list = getNumList(10,()->(int)(Math.random()*100));
        for(Integer i:list){
            System.out.println(i);
        }
    }
    // 需求:产生指定个数的证书，并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();
        for (int i=0;i<num;i++){
            Integer n = sup.get();
            list.add(n);
        }
        return list;
    }

    /** 3 Function<T,R> 函数形接口:*/
    @Test
    public void Test3(){
        String newStr = strHandler("\t\t\t 我是个好人",s -> s.trim());
        System.out.println(newStr);

        String newStr1 = strHandler("\t\t\t 我是个好人",s -> s.trim().substring(3));
        System.out.println(newStr1);

        String newStr2 = strHandler("abcde",s -> s.toUpperCase());
        System.out.println(newStr2);
    }

    // 需求，用于处理字符串
    public String strHandler(String str, Function<String,String> fun){
        return  fun.apply(str);
    }


    /** 4 Predicate<T> 断言型接口:*/
    @Test
    public void test4(){
        List<String> list = Arrays.asList("Hello","Lambda","world","www","ok");
        List<String> strList =  filterStr(list,s -> s.length()>3);
        System.out.println(JSON.toJSONString(strList));

    }

    // 需求:将满足条件的字符串，放入到集合中
    public List<String> filterStr(List<String> list, Predicate<String> predicate){
        List<String> strList = new ArrayList<>();
        for (String str : list){
            if(predicate.test(str)){
                strList.add(str);
            }
        }
        return strList;
    }




}
